package com.sun.mail.iap;

import java.io.IOException;
import java.io.OutputStream;

import javax.mail.event.WriteListener;

public class WriteOutputStream extends OutputStream {

	private static final int DEFAULT_BUFFER_SIZE = 8192;
	private int bufferSize = DEFAULT_BUFFER_SIZE;
	
	private OutputStream out;
	private WriteListener listener;

	public WriteOutputStream(OutputStream o, WriteListener l) {
		out = o;
		listener = l;
	}
	
	@Override
	public void write(int b) throws IOException {
		out.write(b);
	}

	@Override
	public void write(byte[] b) throws IOException {
		int dataSize = b.length;
		for (int off = 0 ; off < dataSize ; off += bufferSize) {
			int len = dataSize - off;
			if (len > bufferSize) {
				len = bufferSize;
			}
			
			write(b, off, len);
		}
	}
	
	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		if (listener != null) {
			listener.write(len);
		}
		out.write(b, off, len);
	}
	
	@Override
	public void close() throws IOException {
		out.close();
	}
	
	@Override
	public void flush() throws IOException {
		out.flush();
	}

}
